import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import {
  getCartTotalService,
  getCartListService,
  UpdateCartService,
  DeleteCartService
} from '@/api/cart'

export const useCartStore = defineStore(
  'cart',
  () => {
    const total = ref(0)
    const cartList = ref([])
    const isAll = ref(false)

    const CheckIsAll = () => {
      isAll.value = cartList.value.every((item) => item.isChecked)
    }

    const getCartTotal = async () => {
      const {
        data: { cartTotal }
      } = await getCartTotalService()
      total.value = cartTotal
    }

    const getCartListData = async () => {
      const { data } = await getCartListService()
      data.list.forEach((item) => {
        item.isChecked = true
      })
      cartList.value = data.list
    }

    const toggleCheck = (id) => {
      const obj = cartList.value.find((item) => item.goods_id === id)
      obj.isChecked = !obj.isChecked
    }

    const toggleAllCheck = (flag) => {
      cartList.value.forEach((item) => {
        item.isChecked = flag
      })
    }

    const setGoodsCount = (obj) => {
      const o = cartList.value.find((item) => item.goods_id === obj.goodsId)
      o.goods_num = obj.goodsNum
    }

    const InitCartTotal = () => {
      getCartTotal()
    }

    const InitCartList = () => {
      getCartListData()
    }

    const UpdateCartGoodsNum = async (obj) => {
      setGoodsCount(obj)
      await UpdateCartService(obj)
    }

    const DeleteCart = async (cartIds) => {
      await DeleteCartService({ cartIds })
      getCartListData()
      getCartTotal()
    }

    const totalPrice = computed(() => {
      return cartList.value
        .reduce(
          (sum, item) =>
            sum +
            (item.isChecked ? item.goods_num * item.goods.goods_price_min : 0),
          0
        )
        .toFixed(2)
    })

    const totalNum = computed(() => {
      return cartList.value.filter((item) => item.isChecked).length
    })

    const cartIds = computed(() => {
      return cartList.value
        .filter((item) => item.isChecked)
        .map((item) => item.id)
        .join()
    })

    return {
      total,
      cartList,
      getCartTotal,
      getCartListData,
      toggleCheck,
      toggleAllCheck,
      setGoodsCount,
      InitCartTotal,
      InitCartList,
      UpdateCartGoodsNum,
      DeleteCart,
      isAll,
      CheckIsAll,
      totalPrice,
      totalNum,
      cartIds
    }
  },
  { persist: true }
)
